package com.blt.govdata.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * Created by wuty on 2016/11/9 0009.
 */
public class PropertiesReader {

    static Logger log = LoggerFactory.getLogger(PropertiesReader.class);

    private static Map<String, Properties> propertiesMap = new HashMap<>();

    public PropertiesReader() {
    }

    public static String getParamByProperties(String propertiesName, String paramName) {
        Properties properties = getPropertiesByName(propertiesName);
        String paramValue = (String) properties.get(paramName);
        return paramValue;
    }

    public static synchronized Properties getPropertiesByName(String propertiesName) {
        Properties properties;
        if (propertiesMap.size() >= 1 && propertiesMap.get(propertiesName) != null) {
            properties = propertiesMap.get(propertiesName);
        } else {
            properties = getPropertiesFromFile(propertiesName);
            propertiesMap.put(propertiesName, properties);
        }
        return properties;
    }

    private static Properties getPropertiesFromFile(String fileName) {
        Properties properties = new Properties();
        String basePath = PropertiesReader.class.getResource("/").getPath();
        String filePath = basePath + "/" + fileName;
        try (InputStream in = new FileInputStream(filePath);) {
            properties.load(in);
        } catch (Exception e) {
            log.error("读取文件：" + fileName + " 时出错！", e);
        }
        return properties;
    }
}
